<template>
  <div class="admin-account-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><User /></el-icon>
            <span>管理员账户管理</span>
          </div>
          <el-button type="primary" @click="handleAdd" :icon="Edit">
            <span>添加管理员</span>
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="16" style="width: 100%;">
          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <el-form-item label="管理员账号" style="margin-bottom: 16px;">
              <el-input 
                v-model="searchForm.username" 
                placeholder="请输入管理员账号" 
                clearable 
                prefix-icon="User"
                size="default" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <el-form-item label="角色" style="margin-bottom: 16px;">
              <el-select 
                v-model="searchForm.role" 
                placeholder="请选择角色" 
                clearable
                size="default"
                style="width: 100%;">
                <el-option label="超级管理员" value="super_admin" />
                <el-option label="订单管理员" value="order_admin" />
                <el-option label="商品管理员" value="product_admin" />
                <el-option label="企宣管理员" value="promotion_admin" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-form-item style="margin-bottom: 0;">
              <el-button type="primary" @click="handleSearch" size="default" :icon="Search">
                搜索
              </el-button>
              <el-button @click="handleReset" size="default" :icon="Refresh">
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 管理员列表 -->
      <el-table :data="filteredAdmins" style="width: 100%" v-loading="loading" stripe>
        <el-table-column prop="aid" label="ID" width="80" align="center" />
        <el-table-column prop="acount" label="管理员账号" min-width="150" show-overflow-tooltip />
        <el-table-column prop="permissionId" label="角色" width="130" align="center">
          <template #default="{ row }">
            <el-tag :type="getRoleType(getRoleByPermissionId(row.permissionId))" size="default">
              {{ getRoleLabel(getRoleByPermissionId(row.permissionId)) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="aremarks" label="备注" width="280" show-overflow-tooltip />
        <el-table-column label="密码" width="130" align="center">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; justify-content: center;">
              <span v-if="!row.showPassword" style="font-family: monospace;">••••••</span>
              <span v-else style="font-family: monospace; font-size: 12px;">{{ row.apwd }}</span>
              <el-button 
                type="primary" 
                link
                size="small" 
                @click="row.showPassword = !row.showPassword"
                style="margin-left: 8px; font-size: 12px;">
                {{ row.showPassword ? '隐藏' : '显示' }}
              </el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="{ row }">
            <div style="display: flex; gap: 2px; justify-content: center;">
              <el-button type="primary" size="small" @click="handleEdit(row)" plain>
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="warning" size="small" @click="handleResetPassword(row)" plain>
                <el-icon><Key /></el-icon>
                重置
              </el-button>
              <el-button type="info" size="small" @click="handleUpdatePassword(row)" plain>
                <el-icon><Key /></el-icon>
                更新密码
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑管理员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加管理员' : '编辑管理员'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="adminForm" :rules="rules" ref="adminFormRef" label-width="100px">
        <el-form-item label="管理员账号" prop="username" v-if="dialogType === 'add'">
          <el-input v-model="adminForm.username" placeholder="请输入管理员账号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="adminForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="超级管理员" value="super_admin" />
            <el-option label="订单管理员" value="order_admin" />
            <el-option label="商品管理员" value="product_admin" />
            <el-option label="企宣管理员" value="promotion_admin" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="adminForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="重置密码"
      width="400px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitPassword">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Key, Search, Refresh, User, Avatar } from '@element-plus/icons-vue'
import { adminget, addAdmin, updateAdmin } from '@/api/admin'
// 数据
const loading = ref(false)
const admins = ref([])
const searchForm = reactive({
  username: '',
  role: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 管理员对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const adminFormRef = ref()
const adminForm = reactive({
  id: null,
  username: '',
  role: 'product_admin',
  email: '',
  phone: '',
  remark: ''
})

// 重置密码对话框
const passwordDialogVisible = ref(false)
const passwordFormRef = ref()
const passwordForm = reactive({
  id: null,
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入管理员账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 角色映射函数
const getRoleType = (role) => {
  const roleMap = {
    'super_admin': 'danger',
    'order_admin': 'success',
    'product_admin': 'primary',
    'promotion_admin': 'warning'
  }
  return roleMap[role] || 'info'
}

const getRoleLabel = (role) => {
  const labelMap = {
    'super_admin': '超级管理员',
    'order_admin': '订单管理员',
    'product_admin': '商品管理员',
    'promotion_admin': '企宣管理员'
  }
  return labelMap[role] || role
}

// 根据permissionId获取角色
const getRoleByPermissionId = (permissionId) => {
  const permissionRoleMap = {
    1: 'super_admin',      // 超级管理员
    2: 'order_admin',      // 订单管理员
    3: 'product_admin',    // 商品管理员
    4: 'promotion_admin'   // 企宣管理员
  }
  return permissionRoleMap[permissionId] || 'product_admin' // 默认为商品管理员
}

// 根据角色获取permissionId
const getPermissionIdByRole = (role) => {
  const rolePermissionMap = {
    'super_admin': 1,      // 超级管理员
    'order_admin': 2,      // 订单管理员
    'product_admin': 3,    // 商品管理员
    'promotion_admin': 4   // 企宣管理员
  }
  return rolePermissionMap[role] || 3 // 默认为商品管理员
}

// 模拟数据
const mockAdmins = [
  {
    id: 1,
    username: 'admin',
    role: 'super_admin',
    email: '',
    phone: '',
    lastLoginTime: '',
    lastLoginIp: '',
    remark: '系统超级管理员'
  },
  {
    id: 2,
    username: 'product_manager',
    role: 'product_admin',
    email: '',
    phone: '',
    lastLoginTime: '',
    lastLoginIp: '',
    remark: '负责商品管理'
  },
  {
    id: 3,
    username: 'order_manager',
    role: 'order_admin',
    email: '',
    phone: '',
    lastLoginTime: '',
    lastLoginIp: '',
    remark: '负责订单处理'
  },
  {
    id: 4,
    username: 'promotion_manager',
    role: 'promotion_admin',
    email: '',
    phone: '',
    lastLoginTime: '',
    lastLoginIp: '',
    remark: '负责企业宣传'
  }
]

// 计算属性：过滤后的管理员列表
const filteredAdmins = computed(() => {
  let result = admins.value || [] // 确保result是数组

  // 搜索过滤
  if (searchForm.username) {
    result = result.filter(item => 
      item.acount.toLowerCase().includes(searchForm.username.toLowerCase())
    )
  }
  if (searchForm.role) {
    result = result.filter(item => getRoleByPermissionId(item.permissionId) === searchForm.role)
  }

  // 分页
  total.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

const getAdminList = () => {
  loading.value = true; // 开始加载
  adminget().then(res => {
    // 确保数据结构正确，适配后端返回的格式
    if (res && res.data) {
      admins.value = res.data || [];
      total.value = admins.value.length; // 赋值总数
    } else {
      admins.value = [];
      total.value = 0;
      ElMessage.warning('未获取到管理员数据');
    }
  }).catch(error => {
    console.error("获取管理员列表失败:", error);
    // 显示用户友好的错误提示
    ElMessage.error('获取管理员列表失败，请稍后重试');
    // 使用模拟数据作为后备
    admins.value = mockAdmins;
    total.value = mockAdmins.length;
  }).finally(() => {
    loading.value = false; // 请求完成后关闭加载状态
  });
};


const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.username = ''
  searchForm.role = ''
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(adminForm, {
    id: null,
    username: '',
    role: 'product_admin',
    email: '',
    phone: '',
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(adminForm, {
    id: row.aid,
    username: row.acount,
    role: getRoleByPermissionId(row.permissionId),
    remark: row.aremarks
  })
  dialogVisible.value = true
}

const handleResetPassword = (row) => {
  passwordForm.id = row.aid
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

const handleUpdatePassword = (row) => {
  ElMessageBox.prompt('请输入新密码', '更新密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.{4,20}$/,
    inputErrorMessage: '密码长度必须在4到20个字符之间'
  }).then(({ value }) => {
    loading.value = true
    
    // 使用updateAdmin更新密码，保持其他信息不变
    const updateData = {
      aid: row.aid,
      acount: row.acount,
      aremarks: row.aremarks || '',
      permissionId: row.permissionId,
      apwd: value // 只更新密码
    }
    
    updateAdmin(updateData).then(res => {
      if (res && res.status === 200) {
        ElMessage.success('密码更新成功')
        getAdminList() // 刷新列表以更新密码显示
      } else {
        ElMessage.error(res?.message || '密码更新失败')
      }
    }).catch(error => {
      console.error('密码更新失败:', error)
      ElMessage.error('密码更新失败，请稍后重试')
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    // 用户取消操作
  })
}



const handleSubmit = () => {
  adminFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      if (dialogType.value === 'add') {
        // 新增管理员
        const newAdminData = {
          acount: adminForm.username,
          aremarks: adminForm.remark,
          permissionId: getPermissionIdByRole(adminForm.role),
          apwd: '123456' // 默认密码
        }
        
        addAdmin(newAdminData).then(res => {
          if (res && res.status === 200) {
            ElMessage.success('添加管理员成功')
            dialogVisible.value = false
            getAdminList() // 刷新列表
          } else {
            ElMessage.error(res?.message || '添加管理员失败')
          }
        }).catch(error => {
          console.error('添加管理员失败:', error)
          ElMessage.error('添加管理员失败，请稍后重试')
        }).finally(() => {
          loading.value = false
        })
      } else {
        // 编辑管理员
        const updateData = {
          aid: adminForm.id,
          acount: adminForm.username,
          aremarks: adminForm.remark,
          permissionId: getPermissionIdByRole(adminForm.role)
        }
        
        updateAdmin(updateData).then(res => {
          if (res && res.status === 200) {
            ElMessage.success('更新管理员成功')
            dialogVisible.value = false
            getAdminList() // 刷新列表
          } else {
            ElMessage.error(res?.message || '更新管理员失败')
          }
        }).catch(error => {
          console.error('更新管理员失败:', error)
          ElMessage.error('更新管理员失败，请稍后重试')
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

const handleSubmitPassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      // 首先获取当前管理员信息
      const currentAdmin = admins.value.find(item => item.aid === passwordForm.id)
      if (!currentAdmin) {
        ElMessage.error('未找到管理员信息')
        loading.value = false
        return
      }
      
      // 使用updateAdmin更新密码，保持其他信息不变
      const updateData = {
        aid: passwordForm.id,
        acount: currentAdmin.acount,
        aremarks: currentAdmin.aremarks || '',
        permissionId: currentAdmin.permissionId,
        apwd: passwordForm.newPassword // 只更新密码
      }
      
      updateAdmin(updateData).then(res => {
        if (res && res.status === 200) {
          ElMessage.success('密码重置成功')
          passwordDialogVisible.value = false
          getAdminList() // 刷新列表以更新密码显示
        } else {
          ElMessage.error(res?.message || '密码重置失败')
        }
      }).catch(error => {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败，请稍后重试')
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

// 生命周期
onMounted(() => {
  getAdminList()
})
</script>

<style scoped>
.admin-account-management {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-title .el-icon {
  font-size: 20px;
  color: #409eff;
}

.search-form {
  margin-bottom: 24px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

:deep(.el-table td) {
  height: 60px;
}

:deep(.el-button--small) {
  padding: 8px 12px;
  font-size: 13px;
}

:deep(.el-tag) {
  font-weight: 500;
}

:deep(.el-pagination) {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

@media (max-width: 768px) {
  .admin-account-management {
    padding: 16px;
  }
  
  .search-form {
    padding: 16px;
  }
  
  :deep(.el-table) {
    font-size: 13px;
  }
  
  :deep(.el-table td) {
    height: 50px;
  }
}
</style>